package com.axcbd.demo.service;

import com.axcbd.demo.model.Humidity;
import com.axcbd.demo.repository.HumidityRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Date;
import java.util.List;


@Service
public class HumidityService {

    @Autowired
    private HumidityRepository humidityRepository;

    public List<Humidity> getLatestNHumidity(int n){
        return humidityRepository.findTopNByCreatedAtDesc(n);
    }

    public void saveHumidity(Humidity humidity){
        // 设置时区为北京时间
        ZonedDateTime beijingTime = ZonedDateTime.now(ZoneId.of("Asia/Shanghai"));
        Instant instant = beijingTime.toInstant();
        Date date = Date.from(instant);
        humidity.setCreatedAt(date);
        humidityRepository.save(humidity);
    }
}
